import React, { useEffect, useState } from 'react';
import ShopOrder from './shop_order';
import './index.less';
import axios from 'axios';
import GoodList from './goodlist';
import { history } from 'umi';
import { Checkbox } from 'antd-mobile';
import Notlogin from '../component/notLogin';
import {
  AppOutline,
  FillinOutline,
  MessageFill,
  SearchOutline,
  StarFill,
  UserOutline,
} from 'antd-mobile-icons';

export default function index() {
  const [cartlist, setCartlist] = useState<any[]>([]);
  const [token, setToken] = useState('');
  const [goodlist, setGoodlist] = useState<any[]>([]);
  const [handleFlag, setHandleFlag] = useState<boolean>(false);
  const [checkedall, setcheckedall] = useState<boolean>(false);
  const [totalprice, settotalprice] = useState<number>(0.0);

  const changeHandle = (event: any) => {
    let flag = event.target.innerText;
    if (flag === '编辑') {
      event.target.innerText = '完成';
      setHandleFlag(true);
    } else {
      event.target.innerText = '编辑';
      setHandleFlag(false);
    }
  };

  const getShopcar = () => {
    let userdata1 = sessionStorage.getItem('userdata') || JSON.stringify({});
    axios
      .get('/api/shopping/shopcar?user_id=' + JSON.parse(userdata1)._id)
      .then((values) => {
        let data = values.data;
        setCartlist([...data]);
      });
  };

  const getGoodlist = () => {
    axios.get('/api/shopping/goodlist').then((values) => {
      let data = values.data;
      setGoodlist([...data]);
    });
  };

  const checkall = (checked: boolean) => {
    let userdata1 = sessionStorage.getItem('userdata') || JSON.stringify({});
    let user_id = JSON.parse(userdata1)._id;
    axios
      .post('/api/shopping/checkall', { user_id: user_id, checked: checked })
      .then((values: any) => {
        if (values.data.code === 200) {
          getShopcar();
        }
      });
  };

  const checkone = (id: string, checked: boolean) => {
    axios
      .post('/api/shopping/checkone', { user_id: id, checked: checked })
      .then((values: any) => {
        if (values.data.code === 200) {
          getShopcar();
        }
      });
  };

  const changenum = (id: string, num: number) => {
    axios
      .post('/api/shopping/changenum', { user_id: id, num: num })
      .then((values: any) => {
        if (values.data.code === 200) {
          getShopcar();
        }
      });
  };

  useEffect(() => {
    let token1 = sessionStorage.getItem('token') || '';
    setToken(token1);
  }, [token]);

  useEffect(() => {
    getGoodlist();
    getShopcar();
  }, []);

  useEffect(() => {
    let checkedall = cartlist.every((item) => item.ischecked);
    setcheckedall(checkedall);
    let totalprice = cartlist
      .filter((item) => item.ischecked)
      .reduce((sum, item) => {
        sum += item.num * item.price;
        return sum;
      }, 0);
    settotalprice(totalprice.toFixed(2));
  }, [cartlist]);

  function skip() {
    history.push('/hello/ordering');
  }

  return (
    <div className="shopping">
      <div className="shop_header">
        <div className="header_title">购物车</div>
        {token ? (
          <div className="menu">
            <div className="shop_header_right">
              <div onClick={changeHandle}>编辑</div>
              <div className="shenglue">
                <div className="circle"></div>
                <div className="circle"></div>
                <div className="circle"></div>
              </div>
            </div>
            <ul id="list">
              <li>
                <MessageFill color="#fff" fontSize={14} />
                <span style={{ paddingLeft: '10px' }}>消息</span>
              </li>
              <li>
                <AppOutline color="#fff" fontSize={14} />
                <span style={{ paddingLeft: '10px' }}>首页</span>
              </li>
              <li>
                <SearchOutline color="#fff" fontSize={14} />
                <span style={{ paddingLeft: '10px' }}>搜索</span>
              </li>
              <li>
                <UserOutline color="#fff" fontSize={14} />
                <span style={{ paddingLeft: '10px' }}>我的</span>
              </li>
              <li>
                <StarFill color="#fff" fontSize={14} />
                <span style={{ paddingLeft: '10px' }}>我的收藏</span>
              </li>
              <li>
                <FillinOutline color="#fff" fontSize={14} />
                <span style={{ paddingLeft: '10px' }}>我要反馈</span>
              </li>
            </ul>
          </div>
        ) : (
          <></>
        )}
      </div>
      <div className="shop_order_content">
        <ShopOrder
          cartlist={cartlist}
          token={token}
          checkone={checkone}
          changenum={changenum}
        />
      </div>
      <div className="gussylike">
        <GoodList goodlist={goodlist} />
      </div>
      {token ? (
        cartlist ? (
          <div className="count">
            <div className="count_left">
              <div className="radio">
                <Checkbox
                  style={{
                    '--icon-size': '16px',
                    '--font-size': '12px',
                    '--gap': '4px',
                  }}
                  checked={checkedall}
                  // checked={cartlist.some(i=>i.ishchecked)}
                  onChange={(val) => {
                    checkall(val);
                  }}
                />
              </div>
              <div className="allselect">全选</div>
              {handleFlag ? (
                <></>
              ) : (
                <div className="totalprice">
                  <div className="total">
                    <div style={{ fontSize: '12.5px' }}>合计:</div>
                    <div className="totalnum">
                      {totalprice > 0 ? totalprice : '0.00'}
                    </div>
                  </div>
                  {/* <div>优惠明细</div> */}
                </div>
              )}
            </div>
            <div className="count_right">
              {handleFlag ? (
                <div className="handledell">删除</div>
              ) : (
                <div className="handlecount" onClick={() => skip()}>
                  结算
                </div>
              )}
            </div>
          </div>
        ) : (
          <></>
        )
      ) : (
        <Notlogin></Notlogin>
      )}
    </div>
  );
}
